package org.example.rabbitmq.server.route.strategy.impl;

import org.example.rabbitmq.config.MultiQueueProperties;
import org.example.rabbitmq.server.route.strategy.RouteStrategy;
import org.example.rabbitmq.vo.RoutingIndex;
import org.example.rabbitmq.vo.RoutingKey;
import org.example.rabbitmq.vo.TenantId;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ModRouteStrategy implements RouteStrategy {
    private Map<TenantId, RoutingIndex> indexMap = new ConcurrentHashMap<>();
    @Autowired
    MultiQueueProperties multiQueueProperties;

    @Override
    public RoutingKey route(TenantId tenantId) {
        RoutingIndex routingIndex = null;
        if (!indexMap.containsKey(tenantId)) {
            routingIndex = new RoutingIndex(indexMap.size() + 1);
            indexMap.put(tenantId, routingIndex);
        } else {
            routingIndex = indexMap.get(tenantId);
        }
        long mod = routingIndex.getRoutingIndex() % multiQueueProperties.getQueueSize();
        return new RoutingKey(multiQueueProperties.getRoutingKeyWithIndex((int) mod + 1));
    }
}